/*
 * 功能：用于下载资源文件的基类，应用层只要实现getUrl,processResult即可，若需要知道下载进度，可以重载publishProgress
 */
package me.weijing.common.http;

import java.net.HttpURLConnection;
import java.util.List;
import java.util.Map;

import me.weijing.common.AppManager;
import android.content.Context;

public abstract class ResourceAsyncHttpRequestBase extends AsyncHttpRequestBase {
    public ResourceAsyncHttpRequestBase(Context context) {
        super(context);
        mCallback = new HttpProgressCallbackImpl();
    }

    @Override
    public void cancel() {
        ((HttpProgressCallbackImpl) mCallback).setCanceled(true);
        super.cancel();
    }

    public void aGet(RequestParams reqParam) {

        try {
            String realurl = buildUrl(reqParam);
            mThreadPool.execute(new HttpRequestGet(getUrl(), realurl, mCallback, gExtraHeader, true));
        } catch (Exception e) {
            e.printStackTrace();
            try {
                processFailed(EFailType.EFAILTYPE_SYS, FAILTYPE_CLIENT_CREATETHREAD, null);
                processFinish();
            } catch (Exception e2) {
                e2.printStackTrace();
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }

    /*
     * 功能：下载成功后的回调处理函数
     * 
     * @param: cacheFilePath 为下载成功后保存在本地CacheDisk里的文件路径
     */
    public abstract void processResult(String cacheFilePath);

    class HttpProgressCallbackImpl implements HttpProgressCallback {
        private boolean bCanceled = false;

        public void setCanceled(boolean bCancel) {
            this.bCanceled = bCancel;
        }

        @Override
        public boolean isCanceled() {
            return bCanceled;
        }

        @Override
        public void startProgress() {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        launchProgress();

                    } catch (Exception e) {
                        e.printStackTrace();
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }
            });
        }

        @Override
        public void progressPublish(final int progress) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        publishProgress(progress);

                    } catch (Exception e) {
                        e.printStackTrace();
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }
            });
        }

        /**
         * 返回的请求数据
         * 
         * @param data
         *            为null表示请求失败
         */
        @Override
        public void interpret(final byte[] data) {
            try {
                if (null == data) {
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                processFailed(EFailType.EFAILTYPE_SYS, FAILTYPE_NETFAIL, null);

                            } catch (Exception e) {
                                e.printStackTrace();
                            } catch (Throwable t) {
                                t.printStackTrace();
                            }
                            try {
                                processFinish();
                            } catch (Exception e) {
                                e.printStackTrace();
                            } catch (Throwable t) {
                                t.printStackTrace();
                            }
                        }
                    });
                } else {
                    final String cachedFile = new String(data);
                    final String cached = FileCacheStore.migrateFile(cachedFile, getUrl());
                    mHandler.post(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                if (AppManager.isActivityDestroyed(mContext)) {

                                } else {
                                    processResult(cached);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            } catch (Throwable t) {
                                t.printStackTrace();
                            }
                            try {
                                processFinish();
                            } catch (Exception e) {
                                e.printStackTrace();
                            } catch (Throwable t) {
                                t.printStackTrace();
                            }
                        }
                    });
                }
            } catch (Exception e) {

                e.printStackTrace();
            }
        }

        @Override
        public void serverFail(final int httpCode) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    try {
                        if (AppManager.isActivityDestroyed(mContext)) {

                        } else {
                            if (HttpURLConnection.HTTP_NOT_MODIFIED == httpCode) {
                                String cached = FileCacheStore.getCacheFilePath(getUrl());
                                processResult(cached);
                            } else {
                                processFailed(EFailType.EFAILTYPE_APP, httpCode, null);
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                    try {
                        processFinish();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }
            });

        }

        @Override
        public void interpret(byte[] data, Map<String, List<String>> responseHeaders) {
            interpret(data);
        }
    }

}
